import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login.vue'
import Layout from '@/views/layout.vue'
import { loadMenu as apiLoadMenu } from '@/api/user'
import store from '@/store'
import { whiteList } from '@/conf'
import { isLogin } from '@/utils'
import { removeToken } from '@/utils/auth'
import NotFound from '@/views/notFound.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    redirect: '/dashboard'
  }
  // /* webpackChunkName: "about" */
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(async (to, from, next) => {
  const token = store.state.user.token
  loadPageTitle(to)
  // 已登录
  if (isLogin(token)) {
    if (whiteList.includes(to.path)) {
      next('/')
    } else {
      if (store.state.user.menu.length === 0) {
        await loadMenu(to, next)
      } else {
        next()
      }
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login?redirect=' + to.fullPath)
    }
  }
})
const loadPageTitle = (to) => {
  let str = '金融信贷-'
  to.matched.forEach(item => {
    if (item.meta?.title) {
      str += item.meta.title + '-'
    }
  })
  str = str.substring(0, str.length - 1)
  document.title = str
}

const loadMenu = async (to, next) => {
  const res = await apiLoadMenu()
  const { menu } = res.data.data
  if (res.data.code === 603) {
    removeToken()
    next('/login?redirect=' + to.fullPath)
  } else {
    store.commit('user/setMenu', { menu })
    store.commit('user/setActiveUrl', { activeUrl: to.path })
    // 生成动态路由
    const routes = generateRoutes(menu)
    routes.forEach((route) => {
      router.addRoute(route)
    })
    // 加入404页面
    router.addRoute({
      path: '*',
      component: NotFound
    })
    next({ ...to, replace: true })
  }
}
const generateRoutes = (routes) => {
  routes.forEach((r) => {
    if (r.component === 'Layout') {
      r.component = Layout
    } else {
      const componentName = r.component
      r.component = () => import(`@/views/${componentName}.vue`)
    }
    if (r.children && r.children.length > 0) {
      generateRoutes(r.children)
    }
  })
  return routes
}
export default router
